import 'dart:async';
import 'dart:convert';

import 'package:common_utils/common_utils.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:yp/config/config.dart';
import 'package:yp/router.dart';
import 'package:yp/utils/util.dart';
import 'package:get/get.dart';
import 'package:yp/services/api.dart';
import 'package:intl/intl.dart';
import 'package:sp_util/sp_util.dart';
import '../../../../helper.dart';
import 'state.dart';
import 'package:logger/logger.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

import 'package:yp/pages/address_selector/address_model.dart';

class EndSaleOrderLogic extends GetxController {
  final state = EndSaleOrderState();
  final type = Get.arguments == null ? 1 : Get.arguments['type'];
  final arguments = Get.arguments;
  var logger = Logger(
    printer: PrettyPrinter(),
  );
  var activeId;

  @override
  void onInit() {
    super.onInit();
    // fluwx.weChatResponseEventHandler.listen((event) {
    //   if (event is fluwx.WeChatLaunchMiniProgramResponse) {
    //     /// 取消支付：extMsg:{"errMsg":"requestPayment:fail cancel","status":"30"}
    //     /// 支付成功 extMsg:{"errMsg":"requestPayment:ok","status":"20"}
    //     // print("支付结果回来了====5==${event.extMsg}");
    //     Map resultMap = json.decode(event.extMsg);
    //     if (resultMap != null) {
    //       if (resultMap["status"].toString() == "20") {
    //         // print("支付结果1");
    //         // print(SpUtil.getString('dingdan'));
    //         setMoneyOver(
    //             SpUtil.getString('dingdan'), 1, 'pintuan', 'success', 'a');
    //       } else {
    //         toast("支付失败");
    //       }
    //     } else {
    //       // print("支付结果3");
    //       setMoneyOver(SpUtil.getString('dingdan'), 0, 'pintuan', 'err', 'a');
    //     }
    //   }
    // });
  }

  @override
  void onReady() {
    super.onReady();
    activeId = arguments['ecactivity_id'];
    state.cardType = arguments['card_type'];
    state.needPopSecond =
        arguments['needPopSecond'] != null && arguments['needPopSecond'];

    // selfHelpAddress();
    getGiftCard();

    getCurrentLocationInfo(success: (data) {
      state.orderAddress = data['addressInfo'];
      getEndSale();
      update();
    });
  }

  void getEndSale() {
    var params = {
      "channel_num_id": 99,
      "use_platform": 2,
      "tml_num_id": arguments['tml_num_id'],
      "access_token": SpUtil.getString('token'),
      "integral": state.isJiFen ? null : 0,
      "select_discount_coupons": [], //选取折扣券id几个
      "select_cash_coupons": [], //选取现金券id集合
      "select_freight_coupons": [],
      "is_switch": state.isSwitch
    };
    // print('_____________________________________');
    // print(params);
    // print('_____________________________________');

    Api.fontMoneyTailOrder(params).listen((event) {
      // print('======================$event');
      // print('=== > ${event}---${event['integral']}');
      state.goodsItem = event["order_items"];
      state.dueTime = event['due_time'];
      state.balanceAmount = event['balance_amount'];
      state.depositAmount = event['deposit_amount'];
      state.needPayAmount = event['need_pay_amount'];
      state.isCoupons = event["able_discount_coupons"];
      state.couponsPayAmount = event['coupons_pay_amount'];
      if (event['integral'] == null) {
        // state.showJiFen = false;
        state.validPoint = 0;
        state.deductPoint = 0;
        state.isJiFen = false;
      } else {
        state.validPoint = event['integral']['usr_point'];
        state.deductPoint = event['integral_pay_amount'];
        state.isJiFen = event['integral_pay_amount'] > 0 ? true : false;
      }
      List list = event["order_items"];
      if (list != null && list.length > 0) {
        list.forEach((element) {
          if (element['ec_shop_num_id'] != 102002001) {
            state.canUseCard = false;
          }
        });
      }
      state.number = list?.length ?? 0;

      setcouponArr(event);
      update();
    });
  }

  /// 使用积分重新后计算数据
  void getEndSale2() {
    var params = {
      "channel_num_id": 99,
      "use_platform": 2,
      "tml_num_id": arguments['tml_num_id'],
      "is_switch": state.isSwitch,
      "access_token": SpUtil.getString('token'),
      "integral": state.isJiFen ? null : 0,
      "select_discount_coupons": state.selectDiscountCoupons, //选取折扣券id几个
      "select_cash_coupons": state.selectCashCoupons, //选取现金券id集合
      "select_freight_coupons": state.selectFreightCoupons,
    };
    Api.fontMoneyTailOrder(params).listen((event) {
      state.goodsItem = event["order_items"];
      state.dueTime = event['due_time'];
      state.balanceAmount = event['balance_amount'];
      state.depositAmount = event['deposit_amount'];
      state.needPayAmount = event['need_pay_amount'];
      state.couponsPayAmount = event['coupons_pay_amount'];
      if (event['integral'] == null) {
        state.validPoint = 0;
        state.deductPoint = 0;
      } else {
        state.validPoint = event['integral']['usr_point'];
        state.deductPoint = event['integral_pay_amount'];
      }
      state.goodsItem = event["order_items"];
      List list = event["order_items"];
      state.number = list?.length ?? 0;
      state.isCoupons = event["able_discount_coupons"];

      setcouponArr(event);
      update();
    });
  }

  ///获取礼品卡
  void getGiftCard() {
    var params = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
      "card_status": 3, //购物卡状态 (1: 有效, 2:失效, 3: 可用)
    };
    Api.walletInformation(params).listen((event) {
      state.GiftcardList = event['available_cards'];
      state.GiftcardList.forEach((element) {
        element['click'] = false;
      });
    });
  }

  clickGift(index) {
    setcard(state, index);
    // state.isGiftMoney=10;
    update();
  }

  bool panduan() {
    if (state.orderAddress == null || state.orderAddress['prv_name'] == null) {
      toast("请选择地址");
      return false;
    }
    return true;
  }

  void selectCoupon(index, item) {
    // print("==============selectCoupon================");
    // print(item);
    // print("=============selectCoupon=================");

    bool iss = panduan();
    if (iss) {
      state.couponData = item;
      if (state.couponList[index]['show_status'] == 1) {
        state.couponList[index]['show_status'] = 3;
        state.couponData['show_status'] = 3;
      } else {
        state.couponList[index]['show_status'] = 1;
        state.couponData['show_status'] = 1;
      }
      if (state.couponData['show_status'] == 3) {
        state.couponName = '';
      }
      if (state.couponList[index]['show_status'] == 1) {
        state.couponName = item['qname'];
        state.couponId = item['activityid'];
        state.qmz = item['qmz'];
      }
      update();
      submitCoupon();
    }
  }

  void submitCoupon() {
    // print('state.couponData--------------------');
    // print(state.couponData);
    // print('state.couponData--------------------');
    var item = state.couponData;
    if (item != null) {
      if (item['show_status'] == 3) {
        state.selectDiscountCoupons = [];
        state.selectCashCoupons = [];
        state.selectFreightCoupons = [];
        state.isSwitch = 1;
      } else {
        if (item['qtype'] == '1' || item['qtype'] == '3') {
          state.selectCashCoupons = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        }
        if (item['qtype'] == '0') {
          state.selectDiscountCoupons = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        }
        if (item['qtype'] == '2') {
          state.selectFreightCoupons = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        }
        state.isSwitch = 0;
      }
    } else {
      state.isSwitch = 1;
    }

    var params = {
      "use_platform": 2,
      "tml_num_id": arguments['tml_num_id'],
      'is_switch': state.isSwitch,
      'access_token': SpUtil.getString('token'),
      //使用积分传数值
      "integral": state.isJiFen ? null : 0,
      "select_discount_coupons": state.selectDiscountCoupons,
      "select_cash_coupons": state.selectCashCoupons,
      "select_freight_coupons": state.selectFreightCoupons,
    };
    // print('==========设置优惠卷-前222===========');
    // print(params);
    // print('==========设置优惠卷-前222===========');
    Api.fontMoneyTailOrder(params).listen((event) {
      state.goodsItem = event["order_items"];
      state.dueTime = event['due_time'];
      state.balanceAmount = event['balance_amount'];
      state.depositAmount = event['deposit_amount'];
      state.needPayAmount = event['need_pay_amount'];
      state.couponsPayAmount = event['coupons_pay_amount'];
      if (event['integral'] == null) {
        // state.showJiFen = false;
        state.isJiFen = false;
        state.validPoint = 0;
        state.deductPoint = 0;
      } else {
        state.isJiFen = event['integral_pay_amount'] > 0 ? true : false;
        state.validPoint = event['integral']['usr_point'];
        state.deductPoint = event['integral_pay_amount'];
      }
      state.goodsItem = event["order_items"];
      List list = event["order_items"];
      state.number = list?.length ?? 0;
      state.isCoupons = event["able_discount_coupons"];

      setcouponArr(event);
      update();
    });
  }

  ///设置优惠卷
  void setcouponArr(event) {
    // print('-------------设置优惠卷------------');
    // print(event);
    // print(event['able_discount_coupons']);
    // print('-------------设置优惠卷------------');

    List newarr = [];
    List nonewarr = [];
    if (event["able_discount_coupons"] != null) {
      List arr = event["able_discount_coupons"];
      arr.forEach((element) {
        element['type'] = 1;
      });
      arr.forEach((element) {
        if (element['show_status'] == 1) {
          state.couponData = element;
        }
        newarr.add(element);
      });
    }
    if (event["able_cash_coupons"] != null) {
      List arr1 = event["able_cash_coupons"];
      arr1.forEach((element) {
        element['type'] = 2;
      });
      arr1.forEach((element) {
        newarr.add(element);
      });
    }
    if (event["able_freight_coupons"] != null) {
      List arr2 = event["able_freight_coupons"];
      arr2.forEach((element) {
        element['type'] = 3;
      });
      arr2.forEach((element) {
        newarr.add(element);
      });
    }

    if (event["disable_discount_coupons"] != null) {
      List arr3 = event["disable_discount_coupons"];

      arr3.forEach((element) {
        nonewarr.add(element);
      });
    }
    if (event["disable_cash_coupons"] != null) {
      List arr4 = event["disable_cash_coupons"];

      arr4.forEach((element) {
        nonewarr.add(element);
      });
    }
    if (event["disable_freight_coupons"] != null) {
      List arr5 = event["disable_freight_coupons"];

      arr5.forEach((element) {
        nonewarr.add(element);
      });
    }
    state.couponList = newarr;
    state.nocouponList = nonewarr;

    state.total = event;
    state.total["all_payment"] =
        state.total["all_payment"] ?? state.total['balance_amount'];
    state.iscou = true;
  }

  void selectSwitch1() {
    if (state.validPoint <= 0) {
      state.isJiFen = false;
      return;
    } else {
      state.isJiFen = !state.isJiFen;
    }
    this.getEndSale2();
  }

  void selfHelpAddress() {
    state.selfHelpAddressList = [];
    var params = {
      'is_pick_up': 1,

      "prv_num_id": state.orderAddress['prv_num_id'],
      "city_num_id": state.orderAddress['city_num_id'],
      "city_area_num_id": state.orderAddress['city_area_num_id'],
      "town_num_id": state.orderAddress['town_num_id'],
      "maplocation_x": state.orderAddress['maplocation_x'],
      "maplocation_y": state.orderAddress['maplocation_y'],
      "adr_num_id": state.orderAddress["adr_num_id"],

      "page": 1,
      "page_size": 10,
      // 'usr_num_id': SpUtil.getInt('empeNumId')
    };
    Api.selfHelpAddress(params).listen((event) {
      if (event['sub_unit_shop_list'].length > 0) {
        state.iszitibutton = true;
        state.selfHelpAddressList = event['sub_unit_shop_list'];
        var item = event['sub_unit_shop_list'][0];
        state.dianAdr = item['prv_name'] +
            item['city_name'] +
            item['city_area_name'] +
            item['adr'];
      } else {
        state.iszitibutton = false;
      }
      update();
    });
  }

  /// 选择支付方式
  void setPayType(int index) {
    state.paytype = index;
    update();
  }

  /// 选择尾款预计付款时间
  void selectDate(DateTime value) {
    state.time = value;
    state.time1 = '${DateFormat("yyyy-MM-dd").format(value)}';
    update();
  }

  /// 输入订金计算尾款
  void countMoney(value) {
    if (!isNumber(value)) {
      state.controller1.clear();
      state.endMoney = null;
      state.startMoney = null;
      return;
    } else if (double.parse(value.toString().isEmpty ? '0' : value) < 0) {
      toast('定金金额不能小于0');
      state.controller1.clear();
      state.startMoney = null;
      state.endMoney = null;
      update();
    } else if (double.parse(value.toString().isEmpty ? '0' : value) >
        state.total["all_payment"]) {
      toast('定金金额不能大于商品金额');
      state.controller1.clear();
      state.startMoney = null;
      state.endMoney = null;
      update();
    } else {
      var dj = double.parse(value.toString().isEmpty ? '0' : value);
      var money = state.total["all_payment"] - dj;
      state.endMoney =
          (NumUtil.getNumByValueDouble(money, 2)).toStringAsFixed(2); // 保留两位小数
      state.startMoney =
          (NumUtil.getNumByValueDouble(dj, 2)).toStringAsFixed(2); // 保留两位小数
    }
    update();
  }

  bool isNumber(String value) {
    if (value == null) {
      return true;
    }
    final n = num.tryParse(value);
    return n != null;
  }

  //提交订单数据
  void orderSubmit([BuildContext context]) {
    var params = {
      "channel_num_id": 99,
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "integral": state.isJiFen ? null : 0,
      "tml_num_id": arguments['tml_num_id'],
      "invoice_main": null, // 发票
      "select_discount_coupons": state.selectDiscountCoupons,
      "select_cash_coupons": state.selectCashCoupons,
      "select_freight_coupons": state.selectFreightCoupons,
      "access_token": SpUtil.getString('token'),
      "is_switch": state.isSwitch //0是使用优惠券，1是不使用
    };
    var item = state.couponData;
    if (item != null) {
      if (item['show_status'] == 3) {
        params['select_discount_coupons'] = [];
        params['select_cash_coupons'] = [];
        params['select_freight_coupons'] = [];
        params['is_switch'] = 1;
      } else {
        if (item['qtype'] == '1' || item['qtype'] == '3') {
          params['select_cash_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        }
        if (item['qtype'] == '0') {
          params['select_discount_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        }
        if (item['qtype'] == '2') {
          params['select_freight_coupons'] = [
            {'ticket_id': item['activityid'], 'coupon_no': item['qbarcode']}
          ];
        }
        params['is_switch'] = 0;
      }
    } else {
      params['is_switch'] = 1;
    }
    if (state.isLoading) return;
    state.isLoading = true;
    print(state.GiftcardList.length);
    print("state.isGiftNum: ${state.isGiftNum}");
    // return;
    Api.fontMoneyTailOrderSubmit(params).listen((event) {
      if (event["code"] == 0) {
        state.total["all_payment"] =
            event['need_pay_amount'] ?? event['balance_amount'];
        var params1;
        if (kIsWeb == true) {
          params1 = {
            "out_trade_no": event["tml_num_id"].toString(),
            "plat_type": 7,
            // "body": "jifen",
            "body": "提交预支付",
            "pay_way": 0,
            "use_platform": 1,
            'access_token': SpUtil.getString('token'),
            // 'appid': Config.ZJ_APPID,
          };
        } else {
          params1 = {
            "out_trade_no": event["tml_num_id"].toString(),
            "plat_type": 7,
            "body": "jifen",
            "pay_way": 0,
            "use_platform": Config.use_plat_form,
            'access_token': SpUtil.getString('token'),
            'appid': Config.ZJ_APPID,
          };
        }

        print("tml_num_id ==> ${event['tml_num_id']}");
        SpUtil.putString('pay_type', 'list');
        // SpUtil.putDouble('need_pay_amount', event['trade_amount']);
        SpUtil.putString('tml_num_id', event['tml_num_id']);
        // return;
        if (state.GiftcardList.length > 0 && state.isGiftNum > 0) {
          state.isLoading = false;
          update();
          gotomoney(state, startCPCNWeixinPay, params1,
              event["tml_num_id"].toString());
        } else {
          //获取openid
          // getopenid();
          Api.orderPayment(params1).listen((event2) {
            SpUtil.putString('dingdan', event['tml_num_id']);
            state.shifu = event2['pay_response']['coupon_fee'];
            print('我要去支付了');
            // print(jsonDecode(event2['pre_pay_no']));
            // var payjson = jsonDecode(event2['pre_pay_no']);
            if (kIsWeb == true) {
              state.isLoading = false;
              update();
              webpay(event2['pre_pay_no']);
            } else {
              state.isLoading = false;
              update();
              if (event2['pre_pay_no'] != null) {
                startCPCNWeixinPay(event2['pre_pay_no'], context);
                // goToMoney(event["tml_num_id"]);
              } else {
                Get.toNamed(RouteConfig.orderComplete, arguments: {
                  'dingdan': event2['tml_num_id'],
                  'shifu': state.shifu
                });
              }
            }
          });
        }
      } else {
        state.isLoading = false;
        update();
        toast(event["message"]);
      }
    });
    update();
  }

  /// 拉起中金支付
  void startCPCNWeixinPay(String authCode, BuildContext context) async {
    if (authCode == null) {
      toast("签名失败");
      return;
    }
    var result =
        fluwx.payWithCPCN(appId: Config.WECHAT_APPID, authCode: authCode);
    if (state.needPopSecond) {
      Navigator.of(context)..pop()..pop();
    } else {
      Navigator.of(context).pop();
    }
  }
}
